﻿

namespace JshRCSWebApi.API.Utility.SqlSugar
{
    public static class SqlsugarSetup
    {
        public static void AddSqlsugarSetup(this IServiceCollection services)
        {
            object ConListStr = SysConfig.Params.DataBaseList;
            List<ConnectionConfig> connectionConfigs = JsonConvert.DeserializeObject<List<ConnectionConfig>>(ConListStr.ToString());
            //sqlsugar注册
            services.AddScoped<ISqlSugarClient>(options =>
            {
                return new SqlSugarClient(connectionConfigs);
            });
            //多租户日志打印设置/全局过滤器
            services.ConfigurationSugar(db =>
            {
                connectionConfigs.ForEach(item =>
                {
                    SetQueryFilter(db.GetConnection(item.ConfigId));
                    SetLog(db, item.ConfigId);
                });
            });
        }
        //日志
        private static void SetLog(SqlSugarClient db, string configid)
        {
            db.GetConnection(configid).Aop.OnLogExecuting = (sql, para) =>
            {
                //var param = para.Select(it => it.Value).ToArray();
                string sqlQuery = UtilMethods.GetSqlString(DbType.MySql, sql, para);
                Console.WriteLine(sqlQuery);
                Console.WriteLine();
            };
        }
        /// <summary>
        /// 添加全局过滤器
        /// </summary>
        /// <param name="provider"></param>
        private static void SetQueryFilter(SqlSugarProvider provider)
        {
            //添加全局过滤器
            var files = Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "Sqlsugar.Business.dll");
            if (files.Length > 0)
            {
                Type[] types = Assembly.LoadFrom(files[0]).GetTypes().Where(it => it.BaseType == typeof(BaseEntity)).ToArray();
                foreach (var entityType in types)
                {
                    var lambda = System.Linq.Dynamic.Core.DynamicExpressionParser.ParseLambda(
                        new[] { Expression.Parameter(entityType, "it") },
                        typeof(bool), $"{nameof(BaseEntity.IsDeleted)} ==  @0",
                        false);
                    provider.QueryFilter.Add(new TableFilterItem<object>(entityType, lambda, true)); //将Lambda传入过滤器
                }
            }
        }
    }
}
